package fs_cmd

import (
	"context"
	"fmt"
	"io"
	"os"

	"atomgit.com/openlinksaas/extension-proto-gen-go.git/extension_fs_api"
	"atomgit.com/openlinksaas/extension-test-cli/utils"
	"github.com/spf13/cobra"
)

var _uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "upload file",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 3 {
			return fmt.Errorf("miss param:[fsId] [fileId] [localFile]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		conn, err := utils.ConnServer()
		if err != nil {
			return err
		}
		defer conn.Close()

		client := extension_fs_api.NewExtensionFsApiClient(conn)
		fsId := args[0]
		fileId := args[1]
		localFile := args[2]

		f, err := os.Open(localFile)
		if err != nil {
			return err
		}
		defer f.Close()

		s, err := client.WriteFile(context.Background())
		if err != nil {
			return err
		}

		buf := make([]byte, 1024*1024)
		for {
			n, err := f.Read(buf)
			if n > 0 {
				err2 := s.Send(&extension_fs_api.WriteFileRequest{
					FsId:   fsId,
					FileId: fileId,
					Data:   buf[:n],
				})
				if err2 != nil {
					return err2
				}
			}
			if err == io.EOF {
				break
			}
			if err != nil {
				return err
			}
		}
		_, err = s.CloseAndRecv()
		if err != nil {
			return err
		}
		fmt.Println("upload", localFile, "success")
		return nil
	},
}
